package com.draven.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.draven.mall.entity.User;
import com.draven.mall.mapper.UserMapper;
import com.draven.mall.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Value("${jwt.expiration}")
    private Long jwtExpiration;

    @Override
    public User login(String username, String password) {
        // 对密码进行MD5加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));

        // 查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        queryWrapper.eq(User::getPassword, encryptedPassword);
        User user = this.getOne(queryWrapper);

        if (user == null) {
            return null;
        }

        // 生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        user.setToken(token);

        // 不返回密码
        user.setPassword(null);

        return user;
    }

    @Override
    public User register(User user) {
        // 检查用户名是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        if (this.count(queryWrapper) > 0) {
            return null;
        }

        // 检查手机号是否已存在
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        if (this.count(queryWrapper) > 0) {
            return null;
        }

        // 对密码进行MD5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));
        user.setStatus(1);

        // 保存用户
        this.save(user);

        // 不返回密码
        user.setPassword(null);

        return user;
    }
}
